#!/usr/bin/env python3
"""
岗位推荐API使用示例
"""

import requests
import json

def test_job_recommendation_api():
    """
    测试岗位推荐API
    """
    # API端点
    url = "http://localhost:8000/rag/recommend-jobs/"
    
    # 准备测试数据
    test_data = {
        "top_k": 5,
        "weight_es": 0.6,
        "weight_chroma": 0.4
    }
    
    # 准备测试PDF文件（这里需要实际的PDF文件路径）
    pdf_file_path = "test_resume.pdf"  # 替换为实际的PDF文件路径
    
    try:
        # 检查PDF文件是否存在
        import os
        if not os.path.exists(pdf_file_path):
            print(f"测试PDF文件不存在: {pdf_file_path}")
            print("请准备一个PDF简历文件进行测试")
            return
        
        # 发送请求
        with open(pdf_file_path, 'rb') as f:
            files = {'file': f}
            response = requests.post(url, data=test_data, files=files)
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            print("API调用成功！")
            print(f"推荐岗位数量: {result.get('total_count', 0)}")
            print(f"搜索参数: {result.get('search_params', {})}")
            print(f"简历摘要: {result.get('resume_summary', '')[:100]}...")
            
            print("\n推荐岗位列表:")
            for i, job in enumerate(result.get('jobs', []), 1):
                print(f"\n{i}. {job.get('title', 'N/A')} - {job.get('company', 'N/A')}")
                print(f"   城市: {job.get('city', 'N/A')}")
                print(f"   标签: {job.get('tags', 'N/A')}")
                print(f"   推荐理由: {job.get('reason', 'N/A')}")
                print(f"   分数: 融合={job.get('scores', {}).get('fused_score', 0):.3f}")
        else:
            print(f"API调用失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            
    except Exception as e:
        print(f"测试失败: {str(e)}")


def show_api_documentation():
    """
    显示API文档
    """
    print("=" * 60)
    print("岗位推荐API文档")
    print("=" * 60)
    
    print("\n1. API端点")
    print("-" * 40)
    print("POST /rag/recommend-jobs/")
    
    print("\n2. 请求参数")
    print("-" * 40)
    print("• file (必需): PDF简历文件")
    print("• top_k (可选): 返回岗位数量，默认8")
    print("• weight_es (可选): ES权重，默认0.6")
    print("• weight_chroma (可选): ChromaDB权重，默认0.4")
    
    print("\n3. 响应格式")
    print("-" * 40)
    response_example = {
        "jobs": [
            {
                "id": "123",
                "title": "Python开发工程师",
                "company": "腾讯科技",
                "city": "深圳",
                "tags": "Python,后端开发",
                "education": "本科",
                "job_str": "岗位描述...",
                "reason": "推荐理由...",
                "scores": {
                    "fused_score": 0.85,
                    "es_score": 15.2,
                    "chroma_score": 0.78
                }
            }
        ],
        "resume_summary": "简历摘要...",
        "total_count": 1,
        "search_params": {
            "top_k": 8,
            "weight_es": 0.6,
            "weight_chroma": 0.4
        }
    }
    print(json.dumps(response_example, indent=2, ensure_ascii=False))
    
    print("\n4. 使用示例")
    print("-" * 40)
    print("curl -X POST \\")
    print("  -F 'file=@resume.pdf' \\")
    print("  -F 'top_k=5' \\")
    print("  -F 'weight_es=0.6' \\")
    print("  -F 'weight_chroma=0.4' \\")
    print("  http://localhost:8000/rag/recommend-jobs/")
    
    print("\n5. 错误处理")
    print("-" * 40)
    print("• 400: 缺少PDF文件或文件格式错误")
    print("• 404: 未找到匹配的岗位")
    print("• 500: 服务器内部错误")


def show_integration_example():
    """
    显示前端集成示例
    """
    print("\n6. 前端集成示例")
    print("-" * 40)
    
    html_example = """
<!DOCTYPE html>
<html>
<head>
    <title>岗位推荐</title>
</head>
<body>
    <form id="recommendForm" enctype="multipart/form-data">
        <input type="file" id="resumeFile" accept=".pdf" required>
        <input type="number" id="topK" value="8" min="1" max="20">
        <button type="submit">获取推荐</button>
    </form>
    
    <div id="results"></div>
    
    <script>
    document.getElementById('recommendForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = new FormData();
        formData.append('file', document.getElementById('resumeFile').files[0]);
        formData.append('top_k', document.getElementById('topK').value);
        
        try {
            const response = await fetch('/rag/recommend-jobs/', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            displayResults(result);
        } catch (error) {
            console.error('Error:', error);
        }
    });
    
    function displayResults(data) {
        const resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = '';
        
        data.jobs.forEach((job, index) => {
            const jobDiv = document.createElement('div');
            jobDiv.innerHTML = `
                <h3>${job.title} - ${job.company}</h3>
                <p>城市: ${job.city}</p>
                <p>推荐理由: ${job.reason}</p>
                <p>匹配分数: ${job.scores.fused_score.toFixed(3)}</p>
            `;
            resultsDiv.appendChild(jobDiv);
        });
    }
    </script>
</body>
</html>
    """
    
    print(html_example)


if __name__ == "__main__":
    show_api_documentation()
    show_integration_example()
    
    print("\n" + "=" * 60)
    print("API文档展示完成！")
    print("=" * 60)
    
    # 如果存在测试文件，则运行测试
    import os
    if os.path.exists("test_resume.pdf"):
        print("\n开始API测试...")
        test_job_recommendation_api()
    else:
        print("\n请准备test_resume.pdf文件进行API测试")
